/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.cj.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cj.common.utils.PageUtils;
import com.cj.user.dao.SysUserDao;
import com.cj.user.entity.Dept;
import com.cj.user.entity.SysCaptchaEntity;
import com.cj.user.entity.SysUserEntity;
import com.cj.user.entity.User;
import com.cj.user.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
//	@Autowired
//	private SysUserRoleService sysUserRoleService;
//	@Autowired
//	private SysRoleService sysRoleService;

//	@Override
//	public PageUtils queryPage(Map<String, Object> params) {
//		String username = (String)params.get("username");
//		Long createUserId = (Long)params.get("createUserId");
//
//		IPage<SysUserEntity> page = this.page(
//			new Query<SysUserEntity>().getPage(params),
//			new QueryWrapper<SysUserEntity>()
//				.like(StringUtils.isNotBlank(username),"username", username)
//				.eq(createUserId != null,"create_user_id", createUserId)
//		);
//
//		return new PageUtils(page);
//	}
//
//	@Override
//	public List<String> queryAllPerms(Long userId) {
//		return baseMapper.queryAllPerms(userId);
//	}
//
	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return this.getOne(new QueryWrapper<SysUserEntity>().eq("username", username));
//		return baseMapper.queryByUserName(username);
	}

	@Override
	public Map<String, Object> info(String user) {
		Map<String, Object> map = new HashMap<>();
//		map.put("user", getUser());
		map.put("name", user);
		map.put("avatar", "../../../resource/image/f778738c-e4f8-4870-b634-56703b4acafe.gif");
		return map;
	}

	@Override
	public Map<String, Object> getList() {
		Map<String, Object> map = new HashMap<>();
		List<Map<String, Object>> listMap = new ArrayList<>();
		Map<String, Object> objectMap = new HashMap<>();
		objectMap.put("id", "@id");
		objectMap.put("title", "@sentence(10, 20)");
		List<String> stringList = new ArrayList<>();
		stringList.add("published");
		stringList.add("draft");
		stringList.add("deleted");
		objectMap.put("status", stringList);
		objectMap.put("author", "name");
		objectMap.put("display_time", "@datetime");
		objectMap.put("pageviews", "@integer(300, 5000)");
		listMap.add(objectMap);
		map.put("items", listMap);

		return  map;
	}

	@Override
	public List<Dept> deptUserTree() {
		List<Dept> dept = initDept();
		List<User> user = initUser();

		return tree(dept, user, true);
	}

	/**
	 * 用户与部门树形结构
	 *
	 * @param dept      部门集合
	 * @param user      用户集合
	 * @param clearZero 是否 清理用户为0的部门
	 * @return
	 */
	private static List<Dept> tree(List<Dept> dept, List<User> user, boolean clearZero) {
		List<Dept> tree = new ArrayList<>();
		// 部门编码与用户集合键值对 deptcode - userList
		Map<String, List<User>> deptUserMap = user.stream().collect(Collectors.groupingBy(User::getDeptCode));
		// 部门编码与部门键值对 deptcode - dept
		Map<String, Dept> deptMap = dept.stream().collect(Collectors.toMap(Dept::getCode, Dept -> Dept));
		dept.stream().forEach(d -> {
			// 放入用户集合和数量
			List<User> deptlist = deptUserMap.get(d.getCode());
			if (deptlist != null) {
				d.setUserItem(deptlist);
				d.setUserNum(deptlist.size());
			}
			// 获取上级，如无上级则为顶级
			Dept parent = deptMap.get(d.getParentCode());
			if (parent != null) {
				List<Dept> items = parent.getItem();
				if (items == null) {
					items = new ArrayList<>();
				}
				items.add(d);
				// 数量逐层累计
				parent.setUserNum(parent.getUserNum() + d.getUserNum());
				parent.setItem(items);
			} else {
				tree.add(d);
			}
		});
		if (clearZero) {
			clearZeroDept(tree);
		}
		return tree;
	}

	/**
	 * 清理用户为0的部门
	 *
	 * @param tree
	 */
	private static void clearZeroDept(List<Dept> tree) {
		for (Iterator<Dept> iterator = tree.iterator(); iterator.hasNext();) {
			Dept dept = iterator.next();
			if (dept.getUserNum() == 0) {
				iterator.remove();
			}
			if (dept.getItem() != null) {
				clearZeroDept(dept.getItem());
			}
		}
	}

	/**
	 * 初始化用户
	 *
	 * @return
	 */
	private static List<User> initUser() {
		List<User> userList = new ArrayList<>();
		User u1 = new User().setCode("2001").setName("张三").setDeptCode("01");
		User u2 = new User().setCode("2002").setName("李四").setDeptCode("0201");
		User u3 = new User().setCode("2003").setName("王五").setDeptCode("0201");
		User u4 = new User().setCode("2004").setName("赵六").setDeptCode("0201");
		userList.add(u1);
		userList.add(u2);
		userList.add(u3);
		userList.add(u4);
		return userList;
	}

	/**
	 * 初始化部门
	 *
	 * @return
	 */
	private static List<Dept> initDept() {
		List<Dept> deptList = new ArrayList<>();
		Dept sjb = new Dept().setCode("01").setName("设计部").setParentCode("-1");
		Dept kfb = new Dept().setCode("02").setName("开发部").setParentCode("-1");
		Dept kfb1 = new Dept().setCode("0201").setName("开发组1").setParentCode("02");
		Dept kfb2 = new Dept().setCode("0202").setName("开发组2").setParentCode("02");
		Dept kfb22 = new Dept().setCode("020201").setName("开发组2-1").setParentCode("0202");
		deptList.add(sjb);
		deptList.add(kfb);
		deptList.add(kfb1);
		deptList.add(kfb2);
		deptList.add(kfb22);
		return deptList;
	}

//	@Override
//	@Transactional
//	public void saveUser(SysUserEntity user) {
//		user.setCreateTime(new Date());
//		//sha256加密
//		String salt = RandomStringUtils.randomAlphanumeric(20);
//		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
//		user.setSalt(salt);
//		this.save(user);
//
//		//检查角色是否越权
//		checkRole(user);
//
//		//保存用户与角色关系
//		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
//	}
//
//	@Override
//	@Transactional
//	public void update(SysUserEntity user) {
//		if(StringUtils.isBlank(user.getPassword())){
//			user.setPassword(null);
//		}else{
//			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
//		}
//		this.updateById(user);
//
//		//检查角色是否越权
//		checkRole(user);
//
//		//保存用户与角色关系
//		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
//	}
//
//	@Override
//	public void deleteBatch(Long[] userId) {
//		this.removeByIds(Arrays.asList(userId));
//	}
//
//	@Override
//	public boolean updatePassword(Long userId, String password, String newPassword) {
//		SysUserEntity userEntity = new SysUserEntity();
//		userEntity.setPassword(newPassword);
//		return this.update(userEntity,
//				new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
//	}
//
//	/**
//	 * 检查角色是否越权
//	 */
//	private void checkRole(SysUserEntity user){
//		if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
//			return;
//		}
//		//如果不是超级管理员，则需要判断用户的角色是否自己创建
//		if(user.getCreateUserId() == Constant.SUPER_ADMIN){
//			return ;
//		}
//
//		//查询用户创建的角色列表
//		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());
//
//		//判断是否越权
//		if(!roleIdList.containsAll(user.getRoleIdList())){
//			throw new RRException("新增用户所选角色，不是本人创建");
//		}
//	}
}
